package com.wm.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.wm.eduService.entity.EduSubject;
import com.wm.eduService.entity.excel.SubjectData;
import com.wm.eduService.entity.subject.OneSubject;
import com.wm.eduService.entity.subject.TwoSubject;
import com.wm.eduService.listener.SubjectExcelListener;
import com.wm.eduService.mapper.EduSubjectMapper;
import com.wm.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.Subject;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author sshdg
 * @since 2020-09-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 通过读取excel添加课程分类
     * @param file 读取的文件
     * @param eduSubjectService 为了给SubjectExcelListener传入一个eduSubjectService
     */
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(eduSubjectService) ).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  查询全部课程分类，并封装输出为适合前端展示的字符串
     * @return
     */
    @Override
    public List<OneSubject> getAllOneAndTwoSubject() {

        List<EduSubject> subjects = this.list(null);

        /**
         * 所有的一级分类
         */
        List<OneSubject> oneSubjectList = subjects.stream()
                .filter(subject -> subject.getParentId().equals("0"))
                .map(subject -> {
                    OneSubject oneSubject = new OneSubject();
                    oneSubject.setId(subject.getId());
                    oneSubject.setTitle(subject.getTitle());
                    return oneSubject;
                })
                .collect(Collectors.toList());
        /**
         * 封装一级分类下的二级分类
         */
        oneSubjectList.forEach(oneSubject ->{
            List<TwoSubject> twoSubjectList = subjects.stream()
                    .filter(subject -> subject.getParentId().equals(oneSubject.getId()))
                    .map(subject -> {
                        TwoSubject twoSubject = TwoSubject.builder()
                                .id(subject.getId())
                                .title(subject.getTitle())
                                .build();
                        return twoSubject;
                    })
                    .collect(Collectors.toList());

            oneSubject.setChildren(twoSubjectList);
        });
        return oneSubjectList;
    }
}
